package ics.zychen.auth;

import java.io.IOException;
import java.net.URL;

import ics.zychen.R;
import ics.zychen.Test3Activity;
import ics.zychen.sql.SinaDataHelper;
import ics.zychen.sql.UserInfo;
import weibo4android.User;
import weibo4android.Weibo;
import weibo4android.WeiboException;
import weibo4android.http.AccessToken;
import weibo4android.http.RequestToken;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;

public class SinaOAuth extends Activity{
	public void onCreate(Bundle savedInstanceState){
		super.onCreate(savedInstanceState);
		
		Uri uri=this.getIntent().getData();
		try {
			System.setProperty("weibo4j.oauth.consumerKey", Weibo.CONSUMER_KEY);
	    	System.setProperty("weibo4j.oauth.consumerSecret", Weibo.CONSUMER_SECRET);
	    	
			RequestToken requestToken= SinaOAuthConstant.getInstance().getRequestToken();
			AccessToken accessToken;
			accessToken = requestToken.getAccessToken(uri.getQueryParameter("oauth_verifier"));
			SinaOAuthConstant.getInstance().setAccessToken(accessToken);
			SinaOAuthConstant.getInstance().setToken(accessToken.getToken());
			SinaOAuthConstant.getInstance().setTokenSecret(accessToken.getTokenSecret());
			Log.e("OAuthActivity", accessToken.getToken());
			Log.e("OAuthActiviry", accessToken.getTokenSecret());
			Log.e("OAuthActivity", accessToken.getUserId()+"");
			
			UserInfo user = new UserInfo();
			user.setUserId(accessToken.getUserId()+"");
			user.setToken(accessToken.getToken());
			user.setTokenSecret(accessToken.getTokenSecret());
			Weibo weibo = SinaOAuthConstant.getInstance().getWeibo();
			weibo.setToken(user.getToken(), user.getTokenSecret());
			User u = weibo.showUser(user.getUserId());
			Log.e("UserInfo", "name: "+u.getScreenName());
			user.setUserName(u.getScreenName());
			try {
				user.setUserIcon(BitmapFactory.decodeStream(u.getProfileImageURL().openConnection() .getInputStream()));
			} catch (IOException e1) {
				e1.printStackTrace();
			}
			
			SinaDataHelper helper = new SinaDataHelper(this);
			if(helper.HaveUserInfo(accessToken.getUserId()+"") != null){
				helper.UpdateUserInfo(user);
				helper.UpdateUserInfo(user.getUserName(), user.getUserIcon(), user.getUserId());
				Log.e("UserInfo", "update:"+user.getUserName());
			} else {
				helper.SaveUserInfo(user);
				Log.e("UserInfo", "add:"+user.getUserName());
			}
			helper.Close();
			
			Intent intent = new Intent();
			intent.setClass(this, Test3Activity.class);
			startActivity(intent);
		} catch (WeiboException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}
